import {
    getUseCard, updateUseCard, getAllUnitList, checkUserCardByUpdate, changUseStatusByPid, deletePropertySingular,
    deletePropertyPlural
} from "@/views/authorization-management/use-card/api/use-card.js"
import dbl from '@/utils/dbl';
import propertyList from "~/views/authorization-management/use-card/add/property-list.vue"
import {getDict} from "~/utils";
import uploadMedia from "~/components/upload-media.vue"

export default {
    components: {
        propertyList: propertyList,
        uploadMedia
    },
    data() {
        return {
            loading: true,
            //上次文件相关
            busId: "",
            modelType: "use-card",
            url: '/admin/sys-file/upLodeFileEdit',
            myHeader: {Authorization: dbl.get('token')},
            //弹出框 初始时隐藏
            dialogVisible: false,
            multipleSelection: [],
            tableDataBefroe:[],
            formObj: {
                useCard: {
                    useCardId: this.$route.query.useCardId,
                    authorizationNumber: '',
                    apUiId: "",
                    unitName: '',
                    authorizationType: '',
                    authorizationTime: '',
                    remarks: "",
                },
                //附件
                fileList: [],
                useCardPropertyList: [],
                propertyIdList: []
            },
            //使用状态
            useStatusCode: [],
            //授权类型
            authTypeLists: [],
            //授权用途集合
            authorizationUseList: [],
            //实际用途
            practicalUseList: [],
            authorizationUse: '产业用房',
            practicalUse: '行政办公',
            unitList: [],
            rules: {
                useCard: {
                    apUiId: [
                        {required: true, message: '请选择使用单位', trigger: 'blur'}
                    ],
                    authorizationType: [
                        {required: true, message: '请选择授权类型', trigger: 'blur'}
                    ],
                    authorizationTime: [
                        {required: true, message: '请选择时间', trigger: 'blur'}
                    ]
                }

            }
        }
    },
    //载入事件
    mounted: function () {


        //获取使用单位的下拉狂列表
        this.getUnit();

    },
    created() {
        this.loading = true;
        this.useStatusCode = getDict('use-status');
        this.authTypeLists = getDict('authorization-type');
        this.authorizationUseList = getDict('authorization-use');
        this.practicalUseList = getDict('practical-use');

        getUseCard(this.$route.query.useCardId).then((resp) => {
            let obj = resp.data.data;
           // this.formObj.fileList = obj.fileList;
            this.formObj.useCard = obj.useCard;
            this.tableDataBefroe = obj.useCardPropertyList;

            if (null != this.tableDataBefroe && this.tableDataBefroe.length > 0) {
                for (let i = 0; i < this.tableDataBefroe.length; i++) {
                    let propertyData = {
                        roomId: '',
                        propertyId: '',
                        propertyName: '',
                        propertyRight:'',
                        propertyRightStr: '',
                        propertyAddress: "",
                        addressArea: "",
                        startTime: "",
                        endTime:"",
                        authorizationUse:"",
                        practicalUse:"",
                        useStatus:"",
                        remarks:"",
                    };
                    propertyData.roomId = this.tableDataBefroe[i].roomId;
                    propertyData.propertyId = this.tableDataBefroe[i].propertyId;
                    propertyData.propertyName = this.tableDataBefroe[i].propertyName;
                    propertyData.propertyRight = this.tableDataBefroe[i].propertyRight;
                    propertyData.propertyAddress = this.tableDataBefroe[i].propertyAddress;
                    propertyData.addressArea = this.tableDataBefroe[i].addressArea;
                    propertyData.startTime = this.tableDataBefroe[i].startTime;
                    propertyData.endTime = this.tableDataBefroe[i].endTime;
                    propertyData.authorizationUse = this.tableDataBefroe[i].authorizationUse;
                    propertyData.practicalUse = this.tableDataBefroe[i].practicalUse;
                    propertyData.useStatus = this.tableDataBefroe[i].useStatus;
                    propertyData.remarks = this.tableDataBefroe[i].remarks;
                    if (propertyData.propertyRight == 1) {
                        propertyData.propertyRightStr ="自有";
                    } else if (propertyData.propertyRight == 2) {
                        propertyData.propertyRightStr ="租用";
                    } else {
                        propertyData.propertyRightStr ="其他";
                    }
                    this.formObj.useCardPropertyList.push(propertyData);
                }
            }



        }).catch(error => {
            this.$message({
                type: 'error',
                message: '获取使用证信息失败'
            });
        }).finally(() => this.loading = false);

        //把实际用途的码值转成数字
        if (null != this.practicalUseList && this.practicalUseList.length > 0) {
            for (let i = 0; i < this.practicalUseList.length; i++) {
                this.practicalUseList[i].value = parseInt(this.practicalUseList[i].value);
            }
        }
        //把授权用途的码值转成数字
        if (null != this.authorizationUseList && this.authorizationUseList.length > 0) {
            for (let i = 0; i < this.authorizationUseList.length; i++) {
                this.authorizationUseList[i].value = parseInt(this.authorizationUseList[i].value);
            }
        }
        this.loading = false;
    },
    methods: {
        /**
         * 保存按钮 触发文件上传
         */
        sendData() {

            this.$refs.useCardUpdateFileUpload.submit(this.modelType, this.formObj.useCard.useCardId);
        },

        query() {
            getUseCard(this.$route.query.useCardId).then((resp) => {
                let obj = resp.data.data;
                this.formObj.fileList = obj.fileList;
                this.formObj.useCard = obj.useCard;
                this.tableDataBefroe = obj.useCardPropertyList;

                if (null != this.tableDataBefroe && this.tableDataBefroe.length > 0) {
                    for (let i = 0; i < this.tableDataBefroe.length; i++) {
                        let propertyData = {
                            roomId: '',
                            propertyId: '',
                            propertyName: '',
                            propertyRight:'',
                            propertyRightStr: '',
                            propertyAddress: "",
                            addressArea: "",
                            startTime: "",
                            endTime:"",
                            authorizationUse:"",
                            practicalUse:"",
                            useStatus:"",
                            remarks:"",
                        };
                        propertyData.roomId = this.tableDataBefroe[i].roomId;
                        propertyData.propertyId = this.tableDataBefroe[i].propertyId;
                        propertyData.propertyName = this.tableDataBefroe[i].propertyName;
                        propertyData.propertyRight = this.tableDataBefroe[i].propertyRight;
                        propertyData.propertyAddress = this.tableDataBefroe[i].propertyAddress;
                        propertyData.addressArea = this.tableDataBefroe[i].addressArea;
                        propertyData.startTime = this.tableDataBefroe[i].startTime;
                        propertyData.endTime = this.tableDataBefroe[i].endTime;
                        propertyData.authorizationUse = this.tableDataBefroe[i].authorizationUse;
                        propertyData.practicalUse = this.tableDataBefroe[i].practicalUse;
                        propertyData.useStatus = this.tableDataBefroe[i].useStatus;
                        propertyData.remarks = this.tableDataBefroe[i].remarks;
                        if (propertyData.propertyRight == 1) {
                            propertyData.propertyRightStr ="自有";
                        } else if (propertyData.propertyRight == 2) {
                            propertyData.propertyRightStr ="租用";
                        } else {
                            propertyData.propertyRightStr ="其他";
                        }
                        this.formObj.useCardPropertyList.push(propertyData);
                    }
                }



            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: '使用证信息获取失败'
                });
            }).finally(() => this.loading = false);
        },
        /**
         * 弹出物业信息列表
         */
        showPropertyListInfo: function () {
            this.$refs.propertyList.show();
        },
        /**
         * 获取使用单位的下拉狂列表
         */
        getUnit() {
            getAllUnitList().then((resp) => {
                let obj = resp.data.data;
                this.unitList = obj;
            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: '使用单位获取失败'
                });
            }).finally(() => this.loading = false);
        },

        /**
         * 保存表单信息
         * @returns {Promise<void>}
         */
        async saveEntity() {
            //this.loading = true;
            //验证授权用途和实际用途是否选择
            if (null != this.formObj.useCardPropertyList) {
                let size = this.formObj.useCardPropertyList.length;
                for (let i = 0; i < size; i++) {
                    if (null == this.formObj.useCardPropertyList[i].authorizationUse) {
                        this.$alert('第' + (i + 1) + '行授权用途没有选择', '提示', {
                            confirmButtonText: '确定',
                        });
                        return;
                    }
                    if (null == this.formObj.useCardPropertyList[i].practicalUse) {
                        this.$alert('第' + (i + 1) + '行实际用途没有选择', '提示', {
                            confirmButtonText: '确定',
                        });
                        return;
                    }
                    if (null == this.formObj.useCardPropertyList[i].startTime) {
                        this.$alert('第' + (i + 1) + '行开始时间没有选择', '提示', {
                            confirmButtonText: '确定',
                        });
                        return;
                    }
                    if (null == this.formObj.useCardPropertyList[i].endTime) {
                        this.$alert('第' + (i + 1) + '行结束时间没有选择', '提示', {
                            confirmButtonText: '确定',
                        });
                        return;
                    }

                    //结束时间不能小开开始时间
                    if(this.formObj.useCardPropertyList[i].endTime<this.formObj.useCardPropertyList[i].startTime){
                        this.$alert('第' + (i + 1) + '行结束时间不能小于开始时间', '提示', {
                            confirmButtonText: '确定',
                        });
                        return;
                    }

                }
            }

            let checkval = {apUiId: "", useCardId: "", propertyIdList: []};
            checkval.apUiId = this.formObj.useCard.apUiId;
            checkval.useCardId = this.formObj.useCard.useCardId;
            if (this.formObj.useCardPropertyList.length > 0) {
                for (let i = 0; i < this.formObj.useCardPropertyList.length; i++) {
                    checkval.propertyIdList.push(this.formObj.useCardPropertyList[i].propertyId);
                }
            }

            console.log(checkval);
            //校验重复记录
            await checkUserCardByUpdate(checkval).then((resp) => {
                let bol = resp.data.data.bol;
                let mes = resp.data.data.mes;

                if (bol == false) {

                    this.$refs['ruleForm'].validate((valid) => {
                        if (valid) {
                            let formData = this.formObj;
                            console.log(formData);
                            updateUseCard(formData).then((data) => {
                                this.$message({
                                    type: 'success',
                                    message: '操作成功'
                                });
                                //操作完成 跳转页面
                                this.loading = false;
                                this.$router.push('/permission-manage/use-card-list')
                            }).catch(error => {
                                this.$message({
                                    type: 'error',
                                    message: '操作失败'
                                });
                            }).finally(() => this.loading = false);
                        } else {
                            return false;
                        }
                    });

                } else {
                    this.$alert('已存在绑定的物业编号：' + mes, '提示', {
                        confirmButtonText: '确定',
                    });
                }

            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: '操作失败'
                });
            }).finally(() => this.loading = false);


        },


        /**
         * 物业多选
         */
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        /**
         * 删除绑定物业（单个删除）
         */
        deleteProperty(scope) {
            this.formObj.useCardPropertyList.splice(scope.$index, 1);
        },

        /**
         * 删除物业
         */
        deletePropertys() {
            let multipleSize = this.multipleSelection.length;
            let propertyIds = [];
            if (multipleSize > 0) {


                //重新加载列表
                let listSize = this.formObj.useCardPropertyList.length;
                for (let i = 0; i < multipleSize; i++) {
                    if (listSize > 0) {
                        for (let k = 0; k < listSize; k++) {
                            if (this.multipleSelection[i].cardPropertyId == this.formObj.useCardPropertyList[k].cardPropertyId) {
                                this.formObj.useCardPropertyList.splice(k, 1);
                            }
                        }
                    }
                }

            } else {
                this.$alert('没有选择要删除的行', '提示', {
                    confirmButtonText: '确定',
                });
                return;
            }
        },

        /**
         * 重置
         */
        resetForm() {
            this.$refs['ruleForm'].resetFields();
        },
        //返回
        goBack() {
            this.$router.push('/permission-manage/use-card-list')
        },

        /**
         * 修改使用状态
         */
        changUseStatus(scope) {

            let param = {cardPropertyId: scope.row.cardPropertyId, status: 0};
            if (scope.row.useStatus == 0) {
                param.status = 1;
            } else {
                param.status = 0;
            }

            scope.row.useStatus = param.status;


            // changUseStatusByPid(param).then((resp) => {
            //     this.$alert('操作完成', '提示', {
            //         confirmButtonText: '确定',
            //     });
            //     this.query();
            // }).catch(error => {
            //     this.$alert('操作失败', '提示', {
            //         confirmButtonText: '确定',
            //     });
            // }).finally(() => this.loading = false);

        },


        /**
         * 码值转换
         * @param row
         * @param column
         * @param cellValue
         * @returns {string|*}
         */
        dictVal_useStatus: function (row, column, cellValue) {
            let obj = this.useStatusCode.find(p => p.value == cellValue)
            if (obj) {
                return obj.label
            }
            return '';
        },
    }


}
